#!/bin/bash
broken_files=()
broken_encod=()
if [[ -z "${SRC_DIRECTORY}" ]]; then
    echo "Variable SRC_DIRECTORY was not set"
    exit 1
fi

cd "${SRC_DIRECTORY}"

for file in $(find . -type f \( -name "*.cpp" -o -name "*.h" -o -name "CMakeLists.txt" \)); do
    encod=$(uchardet "$file")
    if [[ $encod != "UTF-8" ]] && [[ $encod != "ASCII" ]]; then
        broken_files+=("$file")
        broken_encod+=("$encod")
    fi
done

if [ ${#broken_files[*]} == 0 ]; then
    echo "All headers and sources are correctly encoded"
    exit 0
fi

printf "Files with encoding other than UTF-8 or ASCII were detected\n"
printf "Number of files: %4d\n" "${#broken_files[*]}"
printf "Please correct the encoding of the files below:\n"

for index in ${!broken_files[*]}; do
    printf "%s: %s\n" "${broken_files[$index]}" "${broken_encod[$index]}"
done
exit 1
